package com.baiduspring.web.user;

import com.baiduspring.dao.entity.User;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.user.FollowAuthorService;
import com.baiduspring.utils.ResponseResult;
import com.baiduspring.utils.SystemCode;
import com.baiduspring.vo.FollowAuthorVO;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 关注控制器
 *
 * @author xiongyan
 */
@RestController
@Scope("prototype")
@RequestMapping("/follow_author")
@Slf4j
public class FollowAuthorController {
    @Resource
    private FollowAuthorService followAuthorService;

    @GetMapping("/get_all/{account}")
    public JSONArray getAll(@PathVariable("account") Long account) {
        Optional<Map<String, List<FollowAuthorVO>>> allByAccount = followAuthorService.getAllByAccount(account);
        if (allByAccount.isPresent()) {
            return JSONArray.fromObject(allByAccount.get());
        }

        return null;
    }

    @PostMapping("/add/{account}")
    public ResponseResult addFollow(@PathVariable("account") Long account, HttpSession session) {
        ResponseResult result = new ResponseResult();
        result.setCode(SystemCode.SUCCESS);
        result.setMessage("关注成功");

        Object o = session.getAttribute("user");
        User user = (User) o;
        try {
            followAuthorService.addFollow(user.getAccount(), account);
        } catch (BaiduSpringException e) {
            result.setCode(SystemCode.FAIL);
            result.setMessage(e.getErrorMsg());
        }
        return result;
    }
}
